package com.ys.controller.api.storage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.storage.TccAssembleError;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccAssembleErrorService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 组装报错单
 */
@Controller
@RequestMapping("/api/inter/tccAssembleError")
public class ApiInterTccAssembleErrorController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccAssembleErrorController.class);

    @Autowired
    private CommonApiService<TccAssembleError> commonApiService;

    @Autowired
    private TccAssembleErrorService tccAssembleErrorService;

    //菜单id
    private Long menuId = MenuId.TCC_AssembleError;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccAssembleError:view";
    //private final String PERMISSIONS_OPERATE = "tccAssembleError:operate";
    private final String PERMISSIONS_ERRORHANDLE = "tccAssembleError:errorHandle";
    private final String PERMISSIONS_PRESTORAGE = "tccAssembleError:preStorage";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccAssembleError setSeachSql(TccAssembleError cond) throws Exception{
        cond = tccAssembleErrorService.setSeachSqlByCommon(cond);
        //排序
        cond.setOrderby("A.Bid DESC");
        //权限
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TccAssembleError cond,String conditions){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String handleStatus = ConditionUtil.getConditionValue(conditions, "handleStatus");//处理状态
            if (handleStatus == null){ //为空时默认显示：未处理、补发货
                cond.where("A.HandleStatus IN(0,2)");
            }
            return commonApiService.searchLay(cond);
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccAssembleError cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //查询条件
            String handleStatus = ConditionUtil.getConditionValue(conditions, "handleStatus");//处理状态
            if (handleStatus == null){ //为空时默认显示：未处理、补发货
                cond.where("A.HandleStatus IN(0,2)");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccAssembleError> util = new ExportExcelUtils<>(new TccAssembleError());
            String toFilePath = util.exportExcel(listData, listField, "组装报错单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 报错处理
     */
    @RequiresPermissions(PERMISSIONS_ERRORHANDLE)
    @RequestMapping("/errorHandle")
    @ResponseBody
    public R errorHandle(int handleStatus, String choooseDatas){
        try {
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailJA.size(); i++) {
                JSONObject detailJO = detailJA.getJSONObject(i);
                Map<String, Object> params = new HashMap<>();
                params.put("id",detailJO.get("id"));
                params.put("handleStatus",handleStatus);
                //报错处理
                R res = tccAssembleErrorService.errorHandle(params);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (detailJO.get("bid")!=null?"单号："+detailJO.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功处理"+doCount+"条数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 预入库
     */
    @RequiresPermissions(PERMISSIONS_PRESTORAGE)
    @RequestMapping("/preStorage")
    @ResponseBody
    public R preStorage(String choooseDatas,
    		String estimatedArrivalTime,
    		String logisticsMode,
    		String trackingNumber){
        try {
            //预入库
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailJA.size(); i++) {
                JSONObject detailJO = detailJA.getJSONObject(i);
                Map<String, Object> params = new HashMap<>();
                params.put("id",detailJO.get("id"));
                params.put("estimatedArrivalTime",estimatedArrivalTime);
                params.put("logisticsMode",logisticsMode);
                params.put("trackingNumber",trackingNumber);
                //预入库
                R res = tccAssembleErrorService.preStorage(params);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (detailJO.get("bid")!=null?"单号："+detailJO.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功预入库"+doCount+"条数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




}